package com.gitee.es.dynamics.context;

import com.gitee.es.dynamics.common.Const;
import com.gitee.es.dynamics.config.AbstractElasticSearchSqlConfig;
import com.gitee.es.dynamics.config.DynamicsElasticSearchConfig;
import com.gitee.es.dynamics.config.ThreadLocalConfig;
import com.gitee.es.dynamics.exception.DynamicsElasticSearchException;
import com.gitee.es.dynamics.util.CoreUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DynamicsElasticSearchContextHolder {
    /**
     * es sql配置
     */
    private static AbstractElasticSearchSqlConfig elasticSearchSqlConfig;
    /**
     * 用户配置
     */
    private static DynamicsElasticSearchConfig dynamicsElasticSearchConfig;

    public static void setDynamicsElasticSearchConfig(DynamicsElasticSearchConfig dynamicsElasticSearchConfig) {
        DynamicsElasticSearchContextHolder.dynamicsElasticSearchConfig = dynamicsElasticSearchConfig;
    }

    public static void setElasticSearchSqlConfig(AbstractElasticSearchSqlConfig elasticSearchSqlConfig) {
        DynamicsElasticSearchContextHolder.elasticSearchSqlConfig = elasticSearchSqlConfig;
    }

    /**
     * 切换数据源路由
     *
     * @param route 数据源路由
     * @return void
     * @date 2023/12/29 9:16
     * @author glq
     */
    public static void setContext(String route) {
        if (route == null || "".equals(route.trim())) {
            throw new DynamicsElasticSearchException("Route must not be null!");
        }
        ThreadLocalConfig.set(Const.BEAN_PREFIX1 + route);
    }

    /**
     * 刷新sql配置-如数据库已更新的话
     *
     * @return void
     * @date 2023/12/29 9:21
     * @author glq
     */
    public static void refreshSqlConfig() {
        if (dynamicsElasticSearchConfig.getOpenSqlConfig()) {
            CoreUtil.clearCoreConfig();
            CoreUtil.loadCoreConfig(elasticSearchSqlConfig.loadElasticSearchSqlConfig());

        } else {
            log.error("Sql config is not open!");
        }

    }
}
